/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-12-10     xu       the first version
 */
#include "time_utils.h"
#include <rtthread.h>

const char* tm_to_date_str(const struct tm* tm_struct)
{
    static char date[16] = "";
    rt_snprintf(date, sizeof(date), "%04d-%02d-%02d", tm_struct->tm_year + 1900, tm_struct->tm_mon + 1,
                tm_struct->tm_mday);
    return date;
}

time_t current_time = 0;
struct tm current_tm = {0};

time_t get_current_time()
{
    current_time = time(NULL);
    rt_memcpy(&current_tm, localtime(&current_time), sizeof(current_tm));
    return current_time;
}

int get_current_month_days()
{
    int days = 0;
    time_t next_time = 0;
    struct tm next_tm = {0};

    next_time = current_time;
    for (int i = 0; i < MONTH_DAYS_MAX; i++) {
        rt_memcpy(&next_tm, localtime(&next_time), sizeof(next_tm));
        if (next_tm.tm_mon != current_tm.tm_mon) {
            break;
        }
        days = next_tm.tm_mday;
        // rt_kprintf("days=%d, asctime: %s", days, asctime(&next_tm));
        next_time += SECONDS_PER_DAY;
    }
    rt_kprintf("Get current month days=%d\n", days);
    return days;
}